<!DOCTYPE html>
<html lang="zh-cn">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>播放器</title>
    <script src="/js/dplayer.js" type="text/javascript"></script>
    <script src="/js/hls.js" type="text/javascript"></script>
    <style>
      body,
      html,
      .dplayer {
        padding: 0;
        margin: 0;
        width: 100%;
        height: 100%;
        background-color: #000;
      }

      a {
        text-decoration: none;
      }
    </style>
  </head>
  <body>
    <div class="dplayer" id="dplayer"></div>
    <script type="text/javascript">
      const handleUrl = url => {
        const fakeUrl = url
        const startFlag = '/player.html?videoUrl='
        const index = fakeUrl.indexOf(startFlag)
        let temp = fakeUrl.slice(index + startFlag.length, fakeUrl.length)
        return temp
      }

      let url = handleUrl(window.location.href)
      const isM3u8 = url => {
        if (url && url.indexOf('.m3u8') > -1) return true
        else if (url.startsWith('blob:')) return true
        return false
      }

      function isMobile() {
        if (
          navigator.userAgent.match(
            /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
          )
        ) {
          return true
        } else {
          return false
        }
      }

      const dplayer = new DPlayer({
        element: document.getElementById('dplayer'),
        autoplay: true,
        mutex: true,
        airplay: true,
        playbackSpeed: [0.75, 1, 1.5],
        video: {
          url: url,
          type: isM3u8(url) ? 'customHls' : 'auto',
          customType: {
            customHls: function (video) {
              const hls = new Hls()
              hls.loadSource(video.src)
              hls.attachMedia(video)
            }
          }
        }
      })

      dplayer.on('fullscreen_cancel', () => {
        if (isMobile()) {
          window.screen.orientation.unlock()
        }
      })

      dplayer.on('fullscreen', () => {
        if (isMobile()) {
          window.screen.orientation.lock('landscape-primary')
        }
      })

      dplayer.container.addEventListener('mousemove', () => {
        dplayer.controller.setAutoHide()
      })

      dplayer.container.addEventListener('click', () => {
        dplayer.controller.setAutoHide()
      })

      window.addEventListener('message', function (e) {
        url = e.data.videoUrl
        dplayer.switchVideo({
          url: url,
          type: isM3u8(url) ? 'customHls' : 'auto',
          customType: {
            customHls: function (video) {
              const hls = new Hls()
              hls.loadSource(video.src)
              hls.attachMedia(video)
            }
          }
        })
      })
    </script>
  </body>
</html>
